package com.liusany.myshop.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.liusany.modules.orm.Page;
import com.liusany.modules.orm.PropertyFilter;
import com.liusany.myshop.dao.AdminDao;
import com.liusany.myshop.dao.RoleDao;
import com.liusany.myshop.entity.Admin;
import com.liusany.myshop.entity.Role;
import com.liusany.myshop.security.ShiroDbRealm;

/**
 * 安全相关实体的管理类, 包括用户,角色,资源与授权类.
 * 
 * @author calvin
 */
//Spring Bean的标识.
@Component
//默认将类中的所有函数纳入事务管理.
@Transactional
public class AccountService extends BaseService<Admin, Long>{

	private static Logger logger = LoggerFactory.getLogger(AccountService.class);

	@Resource
	private AdminDao adminDao;
	@Resource
	private RoleDao roleDao; 
	@Resource
	private ShiroDbRealm shiroRealm;
	
	
   /**
    * 获取登陆用户信息
    * @return
    */
   public Admin getCurrentUser() {
        final String currentUser = (String) SecurityUtils.getSubject().getPrincipal();
        if( currentUser != null ) {
            return findUserByUsername(currentUser);
        } else {
            return null;
        }
    }
	
	@Transactional(readOnly = true)
	public Admin getAdmin(Long id) {
		return adminDao.get(id);
	}

	
	/**
	 * 根据登录名查找用户对象
	 * @author:liusany
	 * @param loginName
	 * @return
	 */
	@Transactional(readOnly = true)
	public Admin findUserByLoginName(String loginName) {
		return adminDao.findUniqueBy("username", loginName);
	}
	
	/**
	 * 新增管理员用户
	 * @author:liusany
	 * @param entity
	 */
	public void saveAdmin(Admin entity) {
		adminDao.save(entity);
		shiroRealm.clearCachedAuthorizationInfo(entity.getUsername());
	}

	/**
	 * 删除用户,如果尝试删除超级管理员将抛出异常.
	 */
	public void deleteUser(Long... ids)throws ServiceException {
		if(ArrayUtils.indexOf(ids, 1L) >= 0){
			logger.warn("操作员{}尝试删除超级管理员用户", SecurityUtils.getSubject().getPrincipal());
			throw new ServiceException("不能删除超级管理员用户");
		}
		for(Long id : ids){
			adminDao.delete(id);
		}
	}

	/**
	 * 判断是否超级管理员.
	 */
	private Long isSupervisor() {
		return 1L;
	}

	/**
	 * 使用属性过滤条件查询用户.
	 */
	@Transactional(readOnly = true)
	public Page<Admin> searchUser(final Page<Admin> page, final List<PropertyFilter> filters) {
		return adminDao.findPage(page, filters);
	}

	@Transactional(readOnly = true)
	public Admin findUserByUsername(String loginName) {
		return adminDao.findUniqueBy("username", loginName);
	}

	/**
	 * 检查用户名是否唯一.
	 *
	 * @return loginName在数据库中唯一或等于oldLoginName时返回true.
	 */
	@Transactional(readOnly = true)
	public boolean isUsernameUnique(String newLoginName, String oldLoginName) {
		return adminDao.isPropertyUnique("username", newLoginName, oldLoginName);
	}

	@Transactional(readOnly = true)
	public Role getRole(Long id) {
		return roleDao.get(id);
	}

	@Transactional(readOnly = true)
	public List<Role> getAllRole() {
		return roleDao.getAll("id", true);
	}

	public void saveRole(Role entity) {
		roleDao.save(entity);
		shiroRealm.clearAllCachedAuthorizationInfo();
	}

	public void deleteRole(Long id) {
		roleDao.delete(id);
		shiroRealm.clearAllCachedAuthorizationInfo();
	}

	@Resource
	public void setBaseDao(AdminDao adminDao) {
		super.setBaseDao(adminDao);
	}
}
